import emitter from '@ohos.events.emitter';
import { Callback } from '@ohos.base';

export class EventManager {
  static registerEvent(eventId: number, handler: Callback<emitter.EventData>) {
    let innerEvent: emitter.InnerEvent = { eventId: eventId }
    emitter.on(innerEvent, handler)
  }

  static unregisterEvent(eventId: number, handler?: (eventData?: emitter.EventData) => void) {
    if (handler) {
      emitter.off(eventId, handler);
    } else {
      emitter.off(eventId);
    }
  }

  /**
   * event不能传递对象数据.如果是对象数据.
   * 如果是对象,实际传递的是json字符串,需要自己手动再parse.
   * @param eventId
   * @param key
   * @param value
   */
  static sendEvent<T>(eventId: number, key?: string, value?: T) {
    //使用Record代替{}
    let dataObj: Record<string, string> = {};
    let json: string | null = null
    if (value != null && key != null) {
      if (value instanceof Object) {
        json = JSON.stringify(value);
      }
      dataObj[key as string] = json!;
    }
    let eventData: emitter.EventData = {
      data: dataObj
    };
    let innerEvent: emitter.InnerEvent = {
      eventId: eventId,
      priority: emitter.EventPriority.HIGH
    };
    emitter.emit(innerEvent, eventData);
  }

  /**
   * 这里不进行自动parse了,根据需要手动进行解析.
   * @param eventData
   * @param key
   * @returns
   */
  static getEventValue<T>(eventData: emitter.EventData, key: string) {
    let data: Record<string, T> = eventData.data as Record<string, T>;
    let value = data[key];
    if (typeof value === "string") {
      value = JSON.parse(value);
    }
    return value as T;
  }

  /**
   * TODO:

   * 直接返回指定类型的对象,不需要再手动new了.
   * @param eventData
   * @param key
   * @param cls
   * @returns
   */
  static getEventPlainValue<T>(eventData: emitter.EventData, key: string): T {
    let data: Record<string, string> = eventData.data as Record<string, string>
    let value = data[key] as T;
    return value;
  }
}